<template>
  <el-form :model="dataForm" :rules="rules" label-position="top" class="form-box" ref="dataFormRef"
    @keyup.enter="dataFormSubmitHandle()" label-width="120px" :disabled="disabled">
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="project">
          <el-form-item prop="projectId" label="是否所属项目" style="width: 120px;">
            <el-radio-group v-model="eventType" @change="handleChangePoject">
              <el-radio-button label="是" :value="1"></el-radio-button>
              <el-radio-button label="否" :value="0"></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="projectId" label="所属研学项目" v-if="eventType === 1" style="width: calc(100% - 120px);">
            <el-select v-model="dataForm.projectId" clearable placeholder="请选择" @change="hanleChangeProject">
              <el-option :value="item.id" :label="item.text" v-for="(item, index) in projectList"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="deptId" label="所属基地">
          <el-select v-model="dataForm.deptId" clearable placeholder="请选择" @change="handleChangeDept">
            <el-option :value="item.id" :label="item.name" v-for="(item, index) in deptList" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="address" label="研学地址">
          <el-input v-model="dataForm.address" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <div v-if="eventType === 1">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="caps" label="单活动人数上限">
            <el-input-number v-model="dataForm.caps" :min="1" controls-position="right" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="carryDate" label="研学开展时间">
            <el-date-picker v-model="carryDate" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="time" label="报名时间">
            <el-date-picker v-model="time" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="cancelTime" label="取消时间">
            <el-date-picker v-model="dataForm.cancelTime" type="datetime" placeholder="请设置"
              value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <div v-else>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="name" label="研学名称">
            <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="carryDate" label="研学开展时间">
            <el-date-picker v-model="carryDate" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="time" label="报名时间">
            <el-date-picker v-model="time" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="organizer" label="主办方">
            <el-input v-model="dataForm.projectInfo.organizer" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="organizerTel" label="主办方电话">
            <el-input v-model="dataForm.projectInfo.organizerTel" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="cancelTime" label="取消时间">
            <el-date-picker v-model="dataForm.cancelTime" type="datetime" placeholder="请设置"
              value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item prop="caps" label="单活动人数上限">
            <el-input-number v-model="dataForm.caps" :min="1" controls-position="right" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="cost" label="研学费用">
            <el-input-number v-model="dataForm.projectInfo.cost" :min="1" controls-position="right"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="studyType" label="研学类型">
            <el-select v-model="dataForm.projectInfo.studyType" clearable placeholder="请选择">
              <el-option :value="item.value" :label="item.label" v-for="(item, index) in studyTypeList"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="dataForm.projectInfo.studyType === 'SCHOOL'">
        <el-col :span="8">
          <el-form-item prop="schoolId" label="关联学校">
            <el-select v-model="dataForm.projectInfo.schoolId" clearable placeholder="请选择" @change="handleChangeSchool">
              <el-option :value="item.id" :label="item.name" v-for="(item, index) in schoolList"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="gradeId" label="关联年级">
            <el-select v-model="dataForm.projectInfo.gradeId" clearable placeholder="请选择" @change="handleChangeGrade">
              <el-option :value="item.id" :label="item.text" v-for="(item, index) in gradeList"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="classId" label="关联班级">
            <el-select v-model="dataForm.projectInfo.classId" clearable placeholder="请选择">
              <el-option :value="item.id" :label="item.text" v-for="(item, index) in classList"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="intro" label="研学简介">
        <el-input v-model="dataForm.projectInfo.intro" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
          placeholder="请输入" />
      </el-form-item>
      <el-form-item prop="visualsList" label="研学介绍图">
        <el-upload v-model:file-list="dataForm.projectInfo.visualsList" drag :action="url" list-type="picture-card"
          :limit="9" :on-preview="handlePictureCardPreview" :on-change="handleChange" :on-remove="handleRemove">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </div>
    <el-form-item prop="signUpNotice" label="报名须知">
        <el-input v-model="dataForm.signUpNotice" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea"
          placeholder="请输入" />
      </el-form-item>
    <el-form-item class="footer-btn">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </el-form-item>
  </el-form>
  <el-dialog class="image-dialog" v-model="dialogVisible">
    <el-image style="width: 60vw; height: 60vh" :src="dialogImageUrl" fit="scale-down" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, UploadFile, UploadFiles, UploadProps } from "element-plus";
import { studyTypeList } from "@/constants/config";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const id = route.query?.id;
const disabled = route.query?.operation === 'detail';
const eventType = ref(1);
const dataFormRef = ref();
const carryDate = ref();
const time = ref();
const projectList = ref<any[]>([]);
const deptList = ref<any[]>([]);
const schoolList = ref<any[]>([]);
const gradeList = ref<any[]>([]);
const classList = ref<any[]>([]);
const url = ref();
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const dataForm = reactive({
  id: "",
  name: "",
  projectId: null,
  period: null,
  deptId: "",
  address: "",
  caps: null,
  cancelTime: "",
  studyType: "",
  signUpNotice: "",
  projectInfo: {
    organizer: "",
    organizerTel: "",
    cost: null,
    studyType: "",
    deptId: "",
    address: "",
    schoolId: "",
    gradeId: "",
    classId: "",
    visuals: [] as any[],
    visualsList: [] as any[],
    intro: "",
  },
});

const rules = ref({
  name: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
});

const init = () => {
  dataForm.id = "";
  url.value = `${app.api}/sys/oss/upload?token=${getToken()}`;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getProjectList(), getDeptList(), getSchoolList()]).then(() => {
    if (id) {
      getInfo(`${id}`);
    }
  });
};

// 获取信息
const getInfo = (id: string) => {
  baseService.get(`/study/event/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
    carryDate.value = [res.data.carryStartDate, res.data.carryEndDate];
    time.value = [res.data.startTime, res.data.endTime];

    const projectId = res.data.projectId;
    eventType.value = projectId ? 1 : 0;

    if (projectId) {
      getProjectInfo(projectId);
    }

    getGradeList(dataForm.projectInfo.schoolId);
    getClassList(dataForm.projectInfo.gradeId);
  });
};

// 获取项目信息
const getProjectInfo = (id: string) => {
  baseService.get(`/study/project/${id}`).then((res) => {
    Object.assign(dataForm.projectInfo, res.data);
  });
};

// 获取项目列表
const getProjectList = () => {
  return baseService.get("/study/project/active/select", {}).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    projectList.value = res.data;
  });
};

// 获取基地列表
const getDeptList = () => {
  return baseService.get("/study/dept/base/select").then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    deptList.value = res.data;
  });
};

// 获取学校列表
const getSchoolList = () => {
  return baseService.get("/study/dept/page", { type: 'SCHOOL' }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    schoolList.value = res.data.list;
  });
};

// 获取年级
const getGradeList = (deptId: string) => {
  return baseService.get("/study/grade/select", { deptId }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    gradeList.value = res.data;
  });
};

// 获取班级
const getClassList = (gradeId: string) => {
  return baseService.get("/study/class/select", { gradeId }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    classList.value = res.data;
  });
};

const hanleChangeProject = (value: string) => {
  getProjectInfo(value);
};

const handleChangeDept = (value: string) => {
  const dept = deptList.value.find((e: any) => e.id === value);
  dataForm.address = dept.address;
  dataForm.projectInfo.address = dept.address;
};

const handleChangeSchool = (value: string) => {
  getGradeList(value);
};

const handleChangeGrade = (value: string) => {
  getClassList(value);
};

const handleRemove: UploadProps['onRemove'] = () => {
  dataForm.visuals = dataForm.visualsList.map((item) => item.id);
};

const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  console.log('uploadFiles', uploadFiles);
  const visualsList = uploadFiles.map((item: any) => {
    if (item.response) item = item.response.data;
    return {
      id: item.id,
      url: item.src || item.url,
    }
  })

  dataForm.projectInfo.visualsList = visualsList;
  dataForm.projectInfo.visuals = visualsList.map((item) => item.id);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
};

const handleChangePoject = async () => {
  await nextTick();
  dataForm.projectInfo = {} as any;
  dataFormRef.value.resetFields();
};
// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)('/study/event', {
      ...dataForm,
      carryStartDate: carryDate.value[0],
      carryEndDate: carryDate.value[1],
      startTime: time.value[0],
      endTime: time.value[1],
      studyType: dataForm.projectInfo.studyType,
    }).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          router.push('/study/event');
        }
      });
    });
  });
};

const cancelHandle = () => {
  router.go(-1);
};

onMounted(() => {
  init();
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<style>
.project {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}

.image-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
